﻿using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Services;
using FastMember;
using gregn6Lib;
using SqlSugar;
using SqlSugar.Extensions;
using Sunny.UI;
using Sunny.UI.Win32;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using System.Xml.Linq;
using static CoreShop.Library.GlobalEnumVars;
using static System.Net.Mime.MediaTypeNames;

namespace CoreShop.PrintService
{
    public partial class frmPrintManagerIP : UIForm
    {
        private int selectRowID = -1;
        private corecmsprintscheme printscheme;
        private corecmsprintbilltype printbilltype;
        private corecmsprintbilltemplate printbilltemplate;
        private int dataType = 0;//0新增，1修改
        private int billtypeId = 1;
        private int sFoodPrintType = 1;
        protected GridppReport newReport = new GridppReport();

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_corecmsprintscheme"></param>
        /// <param name="_printbilltemplate"></param>
        /// <param name="type">0新增，1修改</param>
        public frmPrintManagerIP(corecmsprintscheme _corecmsprintscheme,
            corecmsprintbilltemplate _printbilltemplate, int _datatype,int _billtypeId,int _foodPrintType)
        {
            dataType = _datatype;
            billtypeId = _billtypeId;
            sFoodPrintType = _foodPrintType;
            printscheme = _corecmsprintscheme;               
            printbilltemplate = _printbilltemplate;
            InitializeComponent();
            Fonts.Add(1, new Font("宋体", 12));
            Fonts.Add(2, new Font("宋体", 24));
            Fonts.Add(3, new Font("宋体", 36));
            Width = 960;
            pnlImage.Width = 280;
        }

        #region 小票设置相关

        private readonly Dictionary<int, Font> Fonts = new Dictionary<int, Font>();

        private Menu menu;

        private void AddLine(MenuLine line)
        {
            menu.AddLine(line);
        }

        private void UpdateLine(MenuLine line)
        {
            menu.UpdateLine(line);
        }

        private void UpdateShow()
        {
            LoadMemuObjData();
            if (menu.PageSize == PageSize.W58)
            {
                Width = 960;
                pnlImage.Width = 280;
            }

            if (menu.PageSize == PageSize.W76)
            {
                Width = 1021;
                pnlImage.Width = 341;
            }

            if (menu.PageSize == PageSize.W80)
            {
                Width = 1037;
                pnlImage.Width = 356;
            }

            Left = (Screen.PrimaryScreen.Bounds.Width - Width) / 2;
            UpdateMenu();
            Text = "小票模版设置 [" + menu.PageSize.DisplayText() + "]";
            if (printbilltype.id == (int)GlobalEnumVars.PrintbillType.Label)
            {
                Text = "小票模版设置 [标签纸<自定义>]";
            }
            Image.Invalidate();
        }

        private void btnTopData_Click(object sender, EventArgs e)
        {
            frmBillTemplateEdit frm = new frmBillTemplateEdit(menu.PageSize, VerticalAlignment.Top, billtypeId);
            frm.ShowDialog();
            if (frm.IsOK)
            {
                AddLine(frm.GetLine());
                UpdateShow();
            }

            frm.Dispose();
        }

        private void UpdateMenu()
        {
            ListBox.Items.Clear();
            if (menu == null) return;

            foreach (var line in menu.Header)
            {
                ListBox.Items.Add(line);
            }

            foreach (var line in menu.Center)
            {
                ListBox.Items.Add(line);
            }

            foreach (var line in menu.Footer)
            {
                ListBox.Items.Add(line);
            }
        }

        private void Image_Paint(object sender, PaintEventArgs e)
        {
            try
            {
                int border = 4;
                int top = 4;
                if (menu == null) return;

                top = DrawLines(e.Graphics, menu.Header, border, top);
                //if (menu.Center.Count > 0) top = DrawLine(e.Graphics, border, top);
                top = DrawData(e.Graphics, menu.Center, border, top);
                //if (menu.Footer.Count > 0) top = DrawLine(e.Graphics, border, top);
                DrawLines(e.Graphics, menu.Footer, border, top);
            }
            catch (Exception ex) { MessageBox.Show(ex.Message); }
        }

        private int DrawData(Graphics g, List<MenuLine> lines, int border, int top)
        {
            TypeAccessor accessors = null;
            List<string> members = new List<string>();
            if (DataObj != null)
            {
                accessors = TypeAccessor.Create(typeof(MenuObject));
                var m = accessors.GetMembers();
                foreach (var t in m)
                {
                    members.Add(t.Name);
                }
            }

            foreach (MenuLine line in lines)
            {
                int width = Image.Width;
                int totalWeight = line.GetTotalWeight();
                int left = border;
                Font font = new Font("宋体",line.FontSize * 8);
                SizeF sf = g.MeasureString("item.Text", font);

                //显示明细标题
                //foreach (var item in line.Items)
                //{
                //    int weight = (width - border * 2 - (line.Items.Count - 1) * border) * item.Weight / totalWeight;
                //    SizeF sf1 = g.MeasureString(item.Text, font);

                //    if (item.TextAlign == eTextAlignMode.Left)
                //        g.DrawString(item.Text, font, Brushes.Black, left, top);
                //    if (item.TextAlign == eTextAlignMode.Middle)
                //        g.DrawString(item.Text, font, Brushes.Black, left + (weight - sf1.Width) / 2, top);
                //    if (item.TextAlign == eTextAlignMode.Right)
                //        g.DrawString(item.Text, font, Brushes.Black, left + weight - sf1.Width, top);

                //    left += weight + border;
                //}
                
                //top += (int)sf.Height;
                //top = DrawLine(g, border, top);

                if (!(DataObj is IList))
                {
                    for (int i = 1; i <= 3; i++)
                    {
                        string text = "*".Repeat(i);
                        left = border;
                        foreach (var item in line.Items)
                        {
                            int weight = (width - border * 2 - (line.Items.Count - 1) * border) * item.Weight / totalWeight;
                            SizeF sf1 = g.MeasureString(text, font);
                            if (item.DataAlign == eTextAlignMode.Left)
                                g.DrawString(text, font, Brushes.Black, left, top);
                            if (item.DataAlign == eTextAlignMode.Middle)
                                g.DrawString(text, font, Brushes.Black, left + (weight - sf1.Width) / 2, top);
                            if (item.DataAlign == eTextAlignMode.Right)
                                g.DrawString(text, font, Brushes.Black, left + weight - sf1.Width, top);

                            left += weight + border;
                        }

                        top += (int)sf.Height;
                    }
                }
                else
                {
                    IList list = DataObj as IList;
                    foreach (object o in list)
                    {
                        string text = "";
                        left = border;
                        int idx = 0;
                        foreach (var item in line.Items)
                        {
                            if (members.IndexOf(item.DataPropertyName) >= 0)
                                text = accessors[o, item.DataPropertyName].ToString();
                            int weight = (width - border * 2 - (line.Items.Count - 1) * border) * item.Weight / totalWeight;
                            SizeF sf1 = g.MeasureString(text, font);
                            if (item.DataAlign == eTextAlignMode.Left)
                                g.DrawString(text, font, Brushes.Black, left, top);
                            if (item.DataAlign == eTextAlignMode.Middle)
                                g.DrawString(text, font, Brushes.Black, left + (weight - sf1.Width) / 2, top);
                            if (item.DataAlign == eTextAlignMode.Right)
                                g.DrawString(text, font, Brushes.Black, left + weight - sf1.Width, top);

                            if (menu.Multi && idx == 0) top += (int)sf.Height;
                            idx++;
                            left += weight + border;
                        }

                        top += (int)sf.Height;
                    }

                    if (DataTotalObj != null)
                    {
                        left = border;
                        top = DrawLine(g, border, top);
                        foreach (var item in line.Items)
                        {
                            string text = "";
                            if (members.IndexOf(item.DataPropertyName) >= 0)
                                text = accessors[DataTotalObj, item.DataPropertyName].ToString();

                            int weight = (width - border * 2 - (line.Items.Count - 1) * border) * item.Weight / totalWeight;
                            SizeF sf1 = g.MeasureString(text, font);
                            if (item.DataAlign == eTextAlignMode.Left)
                                g.DrawString(text, font, Brushes.Black, left, top);
                            if (item.DataAlign == eTextAlignMode.Middle)
                                g.DrawString(text, font, Brushes.Black, left + (weight - sf1.Width) / 2, top);
                            if (item.DataAlign == eTextAlignMode.Right)
                                g.DrawString(text, font, Brushes.Black, left + weight - sf1.Width, top);

                            left += weight + border;
                        }

                        top += (int)sf.Height;
                    }
                }
            }
            return top;
        }

        private int DrawLine(Graphics g, int border, int top)
        {
            SizeF sf = g.MeasureString("-", Fonts[1]);
            g.DrawString("-".Repeat(menu.PageSize.CharCount()), Fonts[1], Color.Black, border, top);
            return top + (int)sf.Height;
        }

        private int DrawLines(Graphics g, List<MenuLine> lines, int border, int top)
        {
            int width = Image.Width;

            TypeAccessor accessors = null;
            List<string> members = new List<string>();
            if (MenuObj != null)
            {
                accessors = TypeAccessor.Create(typeof(MenuObject));
                var m = accessors.GetMembers();
                foreach (var t in m)
                {
                    members.Add(t.Name);
                }
            }

            foreach (MenuLine line in lines)
            {
                if (line.IsLine)
                {
                    top = DrawLine(g, border, top);
                }
                else
                {
                    int totalWeight = line.GetTotalWeight();
                    int left = border;
                    Font font = new Font("宋体", line.FontSize * 9);
                    SizeF sf = g.MeasureString("item.Text", font);

                    foreach (var item in line.Items)
                    {
                        int weight = (width - border * 2 - (line.Items.Count - 1) * border) * item.Weight / totalWeight;
                        SizeF sf1 = g.MeasureString(item.Text, font);

                        if (item.DataPropertyName.IsNullOrEmpty())
                        {
                            if (item.TextAlign == eTextAlignMode.Left)
                                g.DrawString(item.Text, font, Brushes.Black, left, top);
                            if (item.TextAlign == eTextAlignMode.Middle)
                                g.DrawString(item.Text, font, Brushes.Black, left + (weight - sf1.Width) / 2, top);
                            if (item.TextAlign == eTextAlignMode.Right)
                                g.DrawString(item.Text, font, Brushes.Black, left + weight - sf1.Width, top);
                        }
                        else
                        {
                            string text = "XX";

                            if (accessors != null && members.IndexOf(item.DataPropertyName) >= 0)
                                text = accessors[MenuObj, item.DataPropertyName].ToString();

                            SizeF sf2 = g.MeasureString(text, font);
                            if (item.TextAlign == eTextAlignMode.Left || item.TextAlign == eTextAlignMode.Middle)
                            {
                                g.DrawString(item.Text, font, Brushes.Black, left, top);

                                if (item.DataAlign == eTextAlignMode.Left)
                                    g.DrawString(text, font, Brushes.Black, left + sf1.Width, top);
                                if (item.DataAlign == eTextAlignMode.Middle)
                                    g.DrawString(text, font, Brushes.Black, left + sf1.Width + ((weight - sf1.Width) - sf2.Width) / 2, top);
                                if (item.DataAlign == eTextAlignMode.Right)
                                    g.DrawString(text, font, Brushes.Black, left + weight - sf2.Width, top);
                            }

                            if (item.TextAlign == eTextAlignMode.Right)
                            {
                                g.DrawString(item.Text, font, Brushes.Black, left + weight - sf1.Width - sf2.Width, top);
                                g.DrawString(text, font, Brushes.Black, left + weight - sf2.Width, top);
                            }
                        }

                        left += weight + border;
                    }

                    top += (int)sf.Height;
                    font.Dispose();
                }
            }

            return top;
        }

        private void btnBottomData_Click(object sender, EventArgs e)
        {
            frmBillTemplateEdit frm = new frmBillTemplateEdit(menu.PageSize, VerticalAlignment.Bottom, billtypeId);
            frm.ShowDialog();
            if (frm.IsOK)
            {
                AddLine(frm.GetLine());
                UpdateShow();
            }

            frm.Dispose();
        }

        private void btnCenterData_Click(object sender, EventArgs e)
        {
            frmBillTemplateEdit frm = new frmBillTemplateEdit(menu.PageSize, VerticalAlignment.Center, billtypeId);
            frm.MultiLine = menu.Multi;
            frm.ShowDialog();
            if (frm.IsOK)
            {
                AddLine(frm.GetLine());
                UpdateShow();
            }

            frm.Dispose();
        }

        

        private void SetEnabled(bool enabled)
        {
            btnTopData.Enabled = enabled;
            btnCenterData.Enabled = enabled;
            btnBottomData.Enabled = enabled;
            btnRender.Enabled = enabled;
            btnPrint.Enabled = enabled;
            btnBarCode.Enabled = enabled;
            btnImage.Enabled = enabled;
            if (printbilltype.tagId == 1)
            {
                pnlData.Visible = false;
            }
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            if (ListBox.Items.Count > 0)
            {
                if (!ShowAskDialog("当前模版不为空，您确认要新建吗？", false)) return;
            }

            int index = 0;
            IList items = new List<string>() { "58CM", "76CM", "80CM" };
            if (printbilltype.id == (int)GlobalEnumVars.PrintbillType.Label)
            {
                items = new List<string>() { "标签纸<自定义>" };
            }

            if (this.ShowSelectDialog(ref index, items, "选择", "请选择打印机纸张大小"))
            {
                Clear();
                menu = new Menu();
                if (printbilltype != null)
                {
                    if (index == (int)PageSize.W58)
                        menu = Json.Deserialize<Menu>(printbilltype.content58);
                    else menu = Json.Deserialize<Menu>(printbilltype.content80);
                }
                menu.PageSize = (PageSize)index;
                UpdateShow();

                //printbilltype.tagId=1为结帐小票等，暂不支持指令打印
                SetEnabled(true);

                string reportFile = PrinterUnits.GetReportFileName(printbilltype, (int)menu.PageSize);
                string sFile = System.Windows.Forms.Application.StartupPath + "\\report\\" + reportFile;
                if (File.Exists(sFile))
                {
                    templateReport.Text = sFile;
                }
            }
        }

        private void ListBox_ItemDoubleClick(object sender, EventArgs e)
        {
            if (selectRowID < 0) return;
            if (ListBox.Items.Count == 0) return;
            if (ListBox.Items.Count < selectRowID) return;
            if (!btnTopData.Enabled) return;
            MenuLine line = (MenuLine)ListBox.SelectedItem;
            frmBillTemplateEdit frm = new frmBillTemplateEdit(menu.PageSize, line.VerAlign, billtypeId);
            if (line.VerAlign == VerticalAlignment.Center) frm.MultiLine = menu.Multi;
            frm.SetLine(line.Clone());
            frm.ShowDialog();
            if (frm.IsOK)
            {
                UpdateLine(frm.GetLine());
                if (line.VerAlign == VerticalAlignment.Center) menu.Multi = frm.MultiLine;
                UpdateShow();
            }

            frm.Dispose();
        }

        private void menuStrip_Opening(object sender, System.ComponentModel.CancelEventArgs e)
        {
            nUP.Enabled = nDown.Enabled = false;
            if (ListBox.Items.Count == 0) return;
            MenuLine line = (MenuLine)ListBox.SelectedItem;
            if (line == null) return;

            if (line.VerAlign == VerticalAlignment.Top)
            {
                int idx = menu.Header.IndexOf(line);
                nUP.Enabled = menu.Header.Count > 1 && idx > 0;
                nDown.Enabled = menu.Header.Count > 1 && idx < menu.Header.Count - 1;
            }

            if (line.VerAlign == VerticalAlignment.Bottom)
            {
                int idx = menu.Footer.IndexOf(line);
                nUP.Enabled = menu.Footer.Count > 1 && idx > 0;
                nDown.Enabled = menu.Footer.Count > 1 && idx < menu.Footer.Count - 1;
            }
        }

        private void nDelete_Click(object sender, EventArgs e)
        {
            if (ListBox.Items.Count == 0) return;
            MenuLine line = (MenuLine)ListBox.SelectedItem;
            if (line == null) return;

            if (ShowAskDialog("您确认要删除" + line, false))
            {
                menu.DeleteLine(line);
                UpdateShow();
            }
        }

        private object MenuObj;
        private object DataObj;
        private object DataTotalObj;

        private void Clear()
        {
            MenuObj = null;
            DataObj = null;
            DataTotalObj = null;
        }

        private void btnRender_Click(object sender, EventArgs e)
        {
            RenderMenu();
        }
                
        private void RenderMenu()
        {
            UpdateShow();
            //foreach (var taskdetail in taskdetails)
            //{

            //}

            //var obj = new MenuObject();
            //obj.FoodName = "对账单";
            //obj.OrderID = "2011101614121";
            //obj.Person = "2人";
            //obj.TableID = "1号桌";
            //obj.Operator = "张翠花";
            //obj.DateTime = DateTime.Now.DateTimeString();
            //obj.AllAmount = "181.0元";
            //obj.Remark = "国庆活动，商品七五折";
            //obj.OrderRemark = "39.0元";
            //obj.Amount = "142.0元";
            //obj.TaskName = "";//做法:少辣，少盐
            //obj.FeedName = "加料:加蛋一个";
            //MenuObj = obj;

            //DataObj = obj;

            //UpdateShow();
        }

        private void btnPrint_Click(object sender, EventArgs e)     
        {
            //new PrintServices().SetPrintData(printIP.Text, MenuObj, DataObj, DataTotalObj, menu);
        }
        
        private void nUP_Click(object sender, EventArgs e)
        {
            if (ListBox.Items.Count == 0) return;
            MenuLine line = (MenuLine)ListBox.SelectedItem;
            if (line == null) return;
            int selectIndex = ListBox.SelectedIndex;

            if (line.VerAlign == VerticalAlignment.Top)
            {
                int index = menu.Header.IndexOf(line);
                menu.Header.RemoveAt(index);
                menu.Header.Insert(index - 1, line);
                UpdateShow();
                ListBox.SelectedIndex = selectIndex - 1;
            }

            if (line.VerAlign == VerticalAlignment.Bottom)
            {
                int index = menu.Footer.IndexOf(line);
                menu.Footer.RemoveAt(index);
                menu.Footer.Insert(index - 1, line);
                UpdateShow();
                ListBox.SelectedIndex = selectIndex - 1;
            }
        }

        private void nDown_Click(object sender, EventArgs e)
        {
            if (ListBox.Items.Count == 0) return;
            MenuLine line = (MenuLine)ListBox.SelectedItem;
            if (line == null) return;
            int selectIndex = ListBox.SelectedIndex;

            if (line.VerAlign == VerticalAlignment.Top)
            {
                int index = menu.Header.IndexOf(line);
                menu.Header.RemoveAt(index);
                menu.Header.Insert(index + 1, line);
                UpdateShow();
                ListBox.SelectedIndex = selectIndex + 1;
            }

            if (line.VerAlign == VerticalAlignment.Bottom)
            {
                int index = menu.Footer.IndexOf(line);
                menu.Footer.RemoveAt(index);
                menu.Footer.Insert(index + 1, line);
                UpdateShow();
                ListBox.SelectedIndex = selectIndex + 1;
            }
        }

        private void btnBarCode_Click(object sender, EventArgs e)
        {
            string barcode = menu.BarCode;
            if (this.InputStringDialog(ref barcode, false, "请输入条码："))
            {
                menu.BarCode = barcode;
            }
        }

        private void btnImage_Click(object sender, EventArgs e)
        {
            string image = menu.Image;
            if (!File.Exists(image))
            {
                image = menu.Image = "";
            }

            if (this.InputStringDialog(ref image, false, "请输入图片地址："))
            {
                menu.Image = image;
            }
        }

        private void uiSymbolButton1_Click(object sender, EventArgs e)
        {

        }

        private void ListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            selectRowID = ListBox.SelectedIndex;
        }

        private void ListBox_DoubleClick(object sender, EventArgs e)
        {
            ListBox_ItemDoubleClick(null, null);
        }

        #endregion

        private void FPrintManager_Load(object sender, EventArgs e)
        {
            try
            {
                #region 加载商品打印方式
                this.foodPrintType.Items.Clear();

                printbilltype = new corecmsprintbilltypeServices().GetById(billtypeId);

                //if (billtypeId < 4) //小票格式，不能选择一菜一单或一数据一单 
                if (billtypeId == (int)GlobalEnumVars.PrintbillType.Label)
                {
                    var printList1 = EnumHelper.EnumToList<GlobalEnumVars.foodPrintType>()
                        .Where(p => p.value == (int)GlobalEnumVars.foodPrintType.Food
                        || p.value == (int)GlobalEnumVars.foodPrintType.Number).ToList();
                    this.foodPrintType.DataSource = printList1;
                    this.foodPrintType.DisplayMember = "description";
                    this.foodPrintType.ValueMember = "value";
                    if (printList1.Count > 0)
                        this.foodPrintType.SelectedValue = (int)GlobalEnumVars.foodPrintType.Food;
                }
                else if (printbilltype.tagId == 1)
                {
                    var printList1 = EnumHelper.EnumToList<GlobalEnumVars.foodPrintType>()
                        .Where(p => p.value == (int)GlobalEnumVars.foodPrintType.Summary
                        || p.value == (int)GlobalEnumVars.foodPrintType.Order).ToList();
                    this.foodPrintType.DataSource = printList1;
                    this.foodPrintType.DisplayMember = "description";
                    this.foodPrintType.ValueMember = "value";
                    if (printList1.Count > 0) this.foodPrintType.SelectedValue = sFoodPrintType;
                }
                else
                {
                    var printList = EnumHelper.EnumToList<GlobalEnumVars.foodPrintType>();
                    this.foodPrintType.DataSource = printList;
                    this.foodPrintType.DisplayMember = "description";
                    this.foodPrintType.ValueMember = "value";
                    if (printList.Count > 0) this.foodPrintType.SelectedValue = sFoodPrintType;
                }

                #endregion
                if (printscheme != null)
                {
                    printIP.Text = printscheme.printerIP.ToString();
                }
                SetEnabled(false);
                LoadMemuObjData();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void LoadMemuObjData()
        {
            int count = 0;
            var PrintSrv = new PrintServices();
            var taskdetails = new corecmsprinttaskdetailServices().QueryPageAsync(ref count, 1, 2, -1, "");            
            if (taskdetails.Count > 0)
            {
                var taskdetail = taskdetails.First();
                if (taskdetail.taskTitle.IsNullOrEmpty()) taskdetail.taskTitle = "微辣";
                if (taskdetail.feedTitle.IsNullOrEmpty()) taskdetail.feedTitle = "加鸡蛋";
                if (taskdetail.detailRemark.IsNullOrEmpty()) taskdetail.detailRemark = "加急";
                var obj = PrintSrv.GetMenuObject(taskdetail);
                MenuObj = obj;
                List<MenuObject> list = new List<MenuObject> { obj };
                DataObj = list;
            }
        }

        private void frmPrintManagerIP_Shown(object sender, EventArgs e)
        {
            if (dataType == 0)
            {
                btnSaveAs.Visible = false;
                btnNew_Click(null, null);
            }
            else
            {
                btnSaveAs.Visible = true;
                templateName.Text = printbilltemplate.name;
                this.taskSign.Text = printbilltemplate.taskSign;
                GetTemplateData(printbilltemplate);
            }
        }

        private void GetTemplateData(corecmsprintbilltemplate billtemplate)
        {
            Clear();
            menu = Json.Deserialize<Menu>(billtemplate.content);
            UpdateShow();

            if (ListBox.Items.Count == 0)
            {
                ShowWarningTip(btnOpen, "模版为空");
            }

            SetEnabled(true);
        }

        private void GetTemplateData(string filename)
        {
            if (!File.Exists(filename)) return;
            Clear();
            menu = Json.DeserializeFromFile<Menu>(filename, Encoding.Default);
            UpdateShow();

            if (ListBox.Items.Count == 0)
            {
                ShowWarningTip(btnOpen, "模版为空");
            }

            SetEnabled(true);
        }

        private void frmPrintManagerIP_FormClosed(object sender, FormClosedEventArgs e)
        {

        }

        private bool checkNewTemplate(string sName)
        {
            if (!IsValidFileName(sName))
            {
                UIMessageBox.Show("输入的打印模板文件名无效，不能有特殊字符。", "提示", UIStyle.Red, UIMessageBoxButtons.OK);
                return false;
            }

            var bl = new corecmsprintbilltemplateServices().IsAny(p => p.name == sName);
            if (bl)
            {
                UIMessageBox.Show("该模板名称已经存在，模板名称不能重复，请更改。", "提示", UIStyle.Red, UIMessageBoxButtons.OK);
                return false;
            }
            string sfileName = System.Windows.Forms.Application.StartupPath + string.Format("\\report\\{0}.ppz", sName);
            if (File.Exists(sfileName))
            {
                UIMessageBox.Show("该模板名称已经存在，模板名称不能重复，请更改。", "提示", UIStyle.Red, UIMessageBoxButtons.OK);
                return false;
            }
            return true;
        }

        
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (ListBox.Items.Count == 0)
            {
                ShowWarningTip(btnSave, "模版为空");
                return;
            }
            if (string.IsNullOrEmpty(templateName.Text))
            {
                ShowWarningTip(btnSave, "请输入模板名称");
                return;
            }
            if (string.IsNullOrEmpty(templateReport.Text))
            {
                ShowWarningTip(btnSave, "请选择模板文件");
                return;
            }
            string text = Json.Serialize(menu);            

            if (dataType == 0)
            {
                if (!checkNewTemplate(templateName.Text)) return;
                printbilltemplate = new corecmsprintbilltemplate();
                printbilltemplate.billtypeId = billtypeId;
                printbilltemplate.foodPrintType = this.foodPrintType.SelectedValue.ObjToInt(0);
                printbilltemplate.name = templateName.Text;
                printbilltemplate.taskSign = taskSign.Text;
                printbilltemplate.content = text;
                printbilltemplate.paperType = (int)menu.PageSize;
                printbilltemplate.reportFile = PrinterUnits.GetReportFileName(printbilltype, (int)menu.PageSize);
                //string sFile = System.Windows.Forms.Application.StartupPath + "\\report\\" + printbilltemplate.reportFile;
                string sFile = templateReport.Text;
                if (File.Exists(sFile)) newReport.LoadFromFile(sFile);
                printbilltemplate.reportData = newReport.SaveToStr();
                if (!new corecmsprintbilltemplateServices().InsertAsync(printbilltemplate))
                {
                    UIMessageBox.Show("保存失败", "提示", UIStyle.Red, UIMessageBoxButtons.OK);
                    return;
                }
            }
            else {
                printbilltemplate.foodPrintType = this.foodPrintType.SelectedValue.ObjToInt(0);
                printbilltemplate.content = text;
                printbilltemplate.name = templateName.Text;
                printbilltemplate.taskSign = taskSign.Text;
                if (!new corecmsprintbilltemplateServices().UpdateAsync(printbilltemplate))
                {
                    UIMessageBox.Show("保存失败", "提示", UIStyle.Red, UIMessageBoxButtons.OK);
                    return;
                }
            }
            dataType = 1;
            btnSaveAs.Visible = true;
            templateName.ReadOnly = true;
            ShowWarningTip(btnSave, "保存成功");
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            string filename = "";
            if (FileEx.OpenDialog(ref filename, "小票配置文件（*.ppz）|*.ppz", "ppz"))
            {
                GetTemplateData(filename);
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private bool IsValidFileName(string fileName)
        {
            // 判断文件名非法            
            if (fileName.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) >= 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        private void btnSaveAs_Click(object sender, EventArgs e)
        {
            if (ListBox.Items.Count == 0)
            {
                ShowWarningTip(btnSave, "模版为空");
                return;
            }
            string value = "";
            if (this.InputStringDialog(ref value, true, "请输入另存为的模板名称：", true))
            {
                if (!checkNewTemplate(value.Trim())) return;
            }
            if (string.IsNullOrEmpty(value.Trim())) return;
            dataType = 0;
            templateName.Text = value.Trim();
            btnSave_Click(null, null);
        }

        private void openReportFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Title = "选择一个文件";
            openFileDialog1.Multiselect = true;
            openFileDialog1.Filter = "报表文件|*.grf";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                foreach (string fileName in openFileDialog1.FileNames)
                {
                    templateReport.Text = fileName;
                }
            }
        }
    }
}
